import path from 'path'
import fs from 'fs-extra'
import { app } from 'electron'
import Base from '../entities/Base'
import { dictToWhere } from '@/utils/sqlUtils'
import { funcFns } from '@/puppeteer/utils/funtion'
import { ArticleStatus, SourceType } from '@/entities/Constant'

const SourceDao = {
    pageSize: Base.pageSize
}

SourceDao.table = "source"

SourceDao.initialForm = (batch) => {
    return JSON.parse(JSON.stringify({
        id: 0,
        name: "",
        batch: batch,
        link: "",
        login: false,
        platform: "",
        enable: true,
        maxRow: "",
        count: 0,
        status: 0,
    }))
}

SourceDao.boolRow = (row) => {
    row.batch = Boolean(row.batch)
    row.login = Boolean(row.login)
    row.enable = Boolean(row.enable)
    return row
}

SourceDao.toDetail = (row, href) => {
    let c = JSON.parse(JSON.stringify(row))
    c.id = 0
    c.link = href
    c.batch = SourceType.Detail
    c.maxRow = 0
    c.sourceId = row.id
    c.status = ArticleStatus.Initial
    return c
}

SourceDao.fetchAll = async (whereDict) => {
    let whereSql = dictToWhere(whereDict)
    return await Base.fetchAll(SourceDao.table, whereSql)
}

SourceDao.fetchPage = async (whereDict, page, pageSize) => {
    if (!pageSize) {
        pageSize = SourceDao.pageSize
    }
    let whereSql = dictToWhere(whereDict)
    return await Base.fetchPage(SourceDao.table, whereSql, page, pageSize)
}

SourceDao.fetchOne = async (id) => {
    const whereSql = "where id = " + id
    return await Base.fetchOne(SourceDao.table, whereSql)
}

SourceDao.fetchCount = async (whereDict, page, pageSize) => {
    let count = await SourceDao.countWhere(whereDict)
    let datas = await SourceDao.fetchPage(whereDict, page, pageSize)
    return { count, datas }
}

SourceDao.countWhere = async (whereDict) => {
    let whereSql = dictToWhere(whereDict)
    return await Base.countWhere(SourceDao.table, whereSql)
}

SourceDao.save = async (obj) => {
    return await Base.save(SourceDao.table, obj)
}

SourceDao.delete = async (id) => {
    return await Base.delete(SourceDao.table, id)
}

SourceDao.folderPath = (row) => {
    let basePath = app.getPath('userData')
    let folderPath = path.join(basePath, String(row.platform), funcFns.calculateMD5(row.link))
    if (!fs.pathExistsSync(folderPath)) {
        fs.mkdirSync(folderPath, { recursive: true })
    }
    return folderPath
}

export { SourceDao }